#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
初始化匹配规则配置
"""

import os
import sys

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app import create_app, db
from app.models.matching_rule import MatchingRule

def init_matching_rules():
    """初始化匹配规则配置"""
    
    # 权重规则配置
    weight_rules = [
        {
            'rule_code': 'weight_age_range',
            'rule_name': '年龄范围权重',
            'rule_type': 'weight',
            'category': 'age',
            'weight': 0.20,
            'rule_config': {
                'base_weight': 0.20,
                'description': '年龄匹配的基础权重'
            },
            'sort_order': 1,
            'description': '年龄范围匹配的权重配置'
        },
        {
            'rule_code': 'weight_education',
            'rule_name': '教育程度权重',
            'rule_type': 'weight',
            'category': 'education',
            'weight': 0.15,
            'rule_config': {
                'base_weight': 0.15,
                'level_bonus': {
                    'same_level': 1.0,
                    'adjacent_level': 0.8,
                    'distant_level': 0.3
                }
            },
            'sort_order': 2,
            'description': '教育程度匹配的权重配置'
        },
        {
            'rule_code': 'weight_income',
            'rule_name': '收入水平权重',
            'rule_type': 'weight',
            'category': 'income',
            'weight': 0.15,
            'rule_config': {
                'base_weight': 0.15,
                'level_tolerance': 2,
                'distance_penalty': 0.2
            },
            'sort_order': 3,
            'description': '收入水平匹配的权重配置'
        },
        {
            'rule_code': 'weight_marital_status',
            'rule_name': '婚姻状况权重',
            'rule_type': 'weight',
            'category': 'marital_status',
            'weight': 0.10,
            'rule_config': {
                'base_weight': 0.10,
                'strict_match': True,
                'mismatch_penalty': 0.8
            },
            'sort_order': 4,
            'description': '婚姻状况匹配的权重配置'
        },
        {
            'rule_code': 'weight_location',
            'rule_name': '地区位置权重',
            'rule_type': 'weight',
            'category': 'location',
            'weight': 0.10,
            'rule_config': {
                'base_weight': 0.10,
                'same_city': 1.0,
                'same_province': 0.7,
                'different_province': 0.3
            },
            'sort_order': 5,
            'description': '地区位置匹配的权重配置'
        },
        {
            'rule_code': 'weight_occupation',
            'rule_name': '职业类型权重',
            'rule_type': 'weight',
            'category': 'occupation',
            'weight': 0.10,
            'rule_config': {
                'base_weight': 0.10,
                'compatible_bonus': 0.2,
                'complementary_bonus': 0.1
            },
            'sort_order': 6,
            'description': '职业类型匹配的权重配置'
        },
        {
            'rule_code': 'weight_housing_status',
            'rule_name': '住房情况权重',
            'rule_type': 'weight',
            'category': 'housing_status',
            'weight': 0.05,
            'rule_config': {
                'base_weight': 0.05,
                'ownership_bonus': 0.3
            },
            'sort_order': 7,
            'description': '住房情况匹配的权重配置'
        },
        {
            'rule_code': 'weight_smoking_habit',
            'rule_name': '吸烟习惯权重',
            'rule_type': 'weight',
            'category': 'smoking_habit',
            'weight': 0.05,
            'rule_config': {
                'base_weight': 0.05,
                'same_habit': 1.0,
                'tolerance_level': 0.4
            },
            'sort_order': 8,
            'description': '吸烟习惯匹配的权重配置'
        },
        {
            'rule_code': 'weight_drinking_habit',
            'rule_name': '饮酒习惯权重',
            'rule_type': 'weight',
            'category': 'drinking_habit',
            'weight': 0.05,
            'rule_config': {
                'base_weight': 0.05,
                'same_habit': 1.0,
                'tolerance_level': 0.4
            },
            'sort_order': 9,
            'description': '饮酒习惯匹配的权重配置'
        },
        {
            'rule_code': 'weight_car_status',
            'rule_name': '车辆情况权重',
            'rule_type': 'weight',
            'category': 'car_status',
            'weight': 0.03,
            'rule_config': {
                'base_weight': 0.03,
                'ownership_bonus': 0.2
            },
            'sort_order': 10,
            'description': '车辆情况匹配的权重配置'
        },
        {
            'rule_code': 'weight_personality_traits',
            'rule_name': '性格特点权重',
            'rule_type': 'weight',
            'category': 'personality_traits',
            'weight': 0.02,
            'rule_config': {
                'base_weight': 0.02,
                'similarity_ratio': 0.6,
                'complementary_ratio': 0.4
            },
            'sort_order': 11,
            'description': '性格特点匹配的权重配置（加分项）'
        },
        {
            'rule_code': 'weight_hobbies',
            'rule_name': '兴趣爱好权重',
            'rule_type': 'weight',
            'category': 'hobbies',
            'weight': 0.02,
            'rule_config': {
                'base_weight': 0.02,
                'common_hobby_bonus': 0.5,
                'min_common_count': 1
            },
            'sort_order': 12,
            'description': '兴趣爱好匹配的权重配置（加分项）'
        }
    ]
    
    # 阈值规则配置
    threshold_rules = [
        {
            'rule_code': 'threshold_min_match',
            'rule_name': '最低匹配阈值',
            'rule_type': 'threshold',
            'category': 'general',
            'weight': 1.0,
            'rule_config': {
                'min_percentage': 30.0,
                'description': '低于此阈值的匹配将被过滤'
            },
            'sort_order': 1,
            'description': '系统最低匹配度阈值配置'
        },
        {
            'rule_code': 'threshold_high_match',
            'rule_name': '高匹配阈值',
            'rule_type': 'threshold',
            'category': 'general',
            'weight': 1.0,
            'rule_config': {
                'high_percentage': 80.0,
                'description': '高于此阈值的匹配将被标记为高匹配'
            },
            'sort_order': 2,
            'description': '高匹配度阈值配置'
        },
        {
            'rule_code': 'threshold_age_tolerance',
            'rule_name': '年龄容忍阈值',
            'rule_type': 'threshold',
            'category': 'age',
            'weight': 1.0,
            'rule_config': {
                'max_age_gap': 10,
                'ideal_age_gap': 5,
                'description': '年龄差距的容忍范围'
            },
            'sort_order': 3,
            'description': '年龄差距容忍度配置'
        }
    ]
    
    # 映射规则配置
    mapping_rules = [
        {
            'rule_code': 'mapping_education_level',
            'rule_name': '教育程度等级映射',
            'rule_type': 'mapping',
            'category': 'education',
            'weight': 1.0,
            'rule_config': {
                'education_middle': 1,
                'education_high': 2,
                'education_technical': 3,
                'education_college': 4,
                'education_bachelor': 5,
                'education_master': 6,
                'education_doctor': 7,
                'education_postdoc': 8
            },
            'sort_order': 1,
            'description': '教育程度数值等级映射'
        },
        {
            'rule_code': 'mapping_income_level',
            'rule_name': '收入等级映射',
            'rule_type': 'mapping',
            'category': 'income',
            'weight': 1.0,
            'rule_config': {
                'income_3k_below': 1,
                'income_3k_5k': 2,
                'income_5k_8k': 3,
                'income_8k_12k': 4,
                'income_12k_20k': 5,
                'income_20k_30k': 6,
                'income_30k_above': 7
            },
            'sort_order': 2,
            'description': '收入水平数值等级映射'
        },
        {
            'rule_code': 'mapping_location_priority',
            'rule_name': '地区优先级映射',
            'rule_type': 'mapping',
            'category': 'location',
            'weight': 1.0,
            'rule_config': {
                'same_city': 1.0,
                'same_province': 0.7,
                'adjacent_province': 0.5,
                'distant_province': 0.3
            },
            'sort_order': 3,
            'description': '地区距离优先级映射'
        }
    ]
    
    try:
        print("开始初始化匹配规则配置...")
        
        # 删除现有规则（如果需要重新初始化）
        existing_count = MatchingRule.query.count()
        if existing_count > 0:
            print(f"发现 {existing_count} 条现有规则，将进行更新...")
        
        # 插入权重规则
        print("1. 初始化权重规则...")
        for rule_data in weight_rules:
            existing_rule = MatchingRule.query.filter_by(rule_code=rule_data['rule_code']).first()
            
            if existing_rule:
                # 更新现有规则
                for key, value in rule_data.items():
                    if key == 'rule_config':
                        existing_rule.set_rule_config(value)
                    else:
                        setattr(existing_rule, key, value)
                print(f"   更新权重规则: {rule_data['rule_name']}")
            else:
                # 创建新规则
                rule = MatchingRule(**{k: v for k, v in rule_data.items() if k != 'rule_config'})
                rule.set_rule_config(rule_data['rule_config'])
                db.session.add(rule)
                print(f"   添加权重规则: {rule_data['rule_name']}")
        
        # 插入阈值规则
        print("2. 初始化阈值规则...")
        for rule_data in threshold_rules:
            existing_rule = MatchingRule.query.filter_by(rule_code=rule_data['rule_code']).first()
            
            if existing_rule:
                # 更新现有规则
                for key, value in rule_data.items():
                    if key == 'rule_config':
                        existing_rule.set_rule_config(value)
                    else:
                        setattr(existing_rule, key, value)
                print(f"   更新阈值规则: {rule_data['rule_name']}")
            else:
                # 创建新规则
                rule = MatchingRule(**{k: v for k, v in rule_data.items() if k != 'rule_config'})
                rule.set_rule_config(rule_data['rule_config'])
                db.session.add(rule)
                print(f"   添加阈值规则: {rule_data['rule_name']}")
        
        # 插入映射规则
        print("3. 初始化映射规则...")
        for rule_data in mapping_rules:
            existing_rule = MatchingRule.query.filter_by(rule_code=rule_data['rule_code']).first()
            
            if existing_rule:
                # 更新现有规则
                for key, value in rule_data.items():
                    if key == 'rule_config':
                        existing_rule.set_rule_config(value)
                    else:
                        setattr(existing_rule, key, value)
                print(f"   更新映射规则: {rule_data['rule_name']}")
            else:
                # 创建新规则
                rule = MatchingRule(**{k: v for k, v in rule_data.items() if k != 'rule_config'})
                rule.set_rule_config(rule_data['rule_config'])
                db.session.add(rule)
                print(f"   添加映射规则: {rule_data['rule_name']}")
        
        # 提交事务
        db.session.commit()
        
        # 统计结果
        total_rules = MatchingRule.query.count()
        weight_count = MatchingRule.query.filter_by(rule_type='weight').count()
        threshold_count = MatchingRule.query.filter_by(rule_type='threshold').count()
        mapping_count = MatchingRule.query.filter_by(rule_type='mapping').count()
        
        print("\n匹配规则初始化完成！")
        print(f"总规则数: {total_rules}")
        print(f"权重规则: {weight_count}")
        print(f"阈值规则: {threshold_count}")
        print(f"映射规则: {mapping_count}")
        
        return True
        
    except Exception as e:
        db.session.rollback()
        print(f"匹配规则初始化失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False


if __name__ == '__main__':
    app = create_app()
    with app.app_context():
        success = init_matching_rules()
        if success:
            print("✅ 匹配规则初始化成功")
        else:
            print("❌ 匹配规则初始化失败") 